package com.cardmanager.pro.scanner;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import com.cardmanager.pro.business.ConsumeTaskPOJOBusiness;
import com.cardmanager.pro.business.CreditCardAccountBusiness;
import com.cardmanager.pro.business.CreditCardAccountHistoryBusiness;
import com.cardmanager.pro.business.CreditCardManagerConfigBusiness;
import com.cardmanager.pro.business.RepaymentTaskPOJOBusiness;
import com.cardmanager.pro.config.PropertiesConfig;
import com.cardmanager.pro.executor.BaseExecutor;
import com.cardmanager.pro.executor.ThreadRepaymentExecutor;
import com.cardmanager.pro.pojo.CreditCardAccount;
import com.cardmanager.pro.pojo.CreditCardManagerConfig;
import com.cardmanager.pro.pojo.RepaymentTaskPOJO;
import com.cardmanager.pro.service.CreditCardManagerTaskService;
import com.cardmanager.pro.util.CardConstss;
import com.cardmanager.pro.util.RestTemplateUtil;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.DateUtil;
import net.sf.json.JSONObject;

@Configuration
@Controller
@EnableScheduling
public class RepaymentTaskScanner extends ApplicationObjectSupport {
	private final Logger LOG = LoggerFactory.getLogger(getClass());

	@Autowired
	private RepaymentTaskPOJOBusiness repaymentTaskPOJOBusiness;

	@Autowired
	private ConsumeTaskPOJOBusiness consumeTaskPOJOBusiness;

	@Autowired
	private CreditCardAccountBusiness creditCardAccountBusiness;
	
	@Autowired
	private CreditCardAccountHistoryBusiness creditCardAccountHistoryBusiness;
	
	@Autowired
	private CreditCardManagerConfigBusiness creditCardManagerConfigBusiness;
	
	@Autowired
	private CreditCardManagerTaskService creditCardManagerTaskService;
	
	@Autowired
	private BaseExecutor baseExecutor;
	
	@Autowired
	private RestTemplateUtil util;
	
	@Autowired
	private PropertiesConfig propertiesConfig;

	/**
	 * 手动执行未执行的还款任务
	 * @param request
	 * @param version
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/test1")
	public @ResponseBody Object test(HttpServletRequest request,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			) {
		List<RepaymentTaskPOJO> repaymentTaskPOJOs = this.findTaskType2AndTaskStatus0RepaymentTask(version);
		if (repaymentTaskPOJOs != null && repaymentTaskPOJOs.size() > 0) {
			this.executeTask(repaymentTaskPOJOs,false);
		}
		return "OK";
	}

	/**
	 * 手动清除 帐户余额有钱的帐户
	 * @param request
	 * @param version
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/test2")
	public @ResponseBody Object test2(HttpServletRequest request,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			) {
		executeRepaymentByBlanceThan0(version);
		return "OK";
	}
	
	
	/**
	 * 手动将帐户中冻结余额转入余额中
	 * @param request
	 * @param version
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/test3")
	public @ResponseBody Object test3(HttpServletRequest request,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		this.clearCreditAccountFreezeBlance(version);
		return "OK";
	}
	
	/**
	 * 测试查询帐户余额有钱的帐户
	 * @param request
	 * @param page
	 * @param version
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST,value="/v1.0/creditcardmanager/test4")
	public @ResponseBody Object test4(HttpServletRequest request,
			@RequestParam(value="page")int page,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			){
		Pageable pageable = new PageRequest(page, 20, new Sort(Sort.Direction.DESC, "blance"));
		List<CreditCardAccount> creditCardAccounts = creditCardAccountBusiness.findCreditCardAccountByBlanceNotZeroAndVersion(version,pageable);
		return creditCardAccounts;
	}
	
	/**
	 * 手动对单个帐户进行出款
	 * @param request
	 * @param userId
	 * @param creditCardNumber
	 * @param version
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/clear/by/userid/creditcardnumber")
	public @ResponseBody Object clearAccountByUserIdAndCreditCardNumber(HttpServletRequest request,
			@RequestParam(value = "userId") String userId,
			@RequestParam(value = "creditCardNumber") String creditCardNumber,
			@RequestParam(value = "amount",required=false) String amountStr,
			@RequestParam(value = "isT1",required=false,defaultValue="0") String isT1,
			@RequestParam(value = "version",required=false,defaultValue="1") String version
			) {
		Map<String, Object> map = new HashMap<>();
		CreditCardAccount creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(userId,creditCardNumber,version);
		BigDecimal amount = null;
		RepaymentTaskPOJO repaymentTaskPOJO = null;
		if (amountStr != null && "".equals(amountStr)) {
			amount = new BigDecimal(amountStr);
		}
		if (CardConstss.CARD_VERSION_6.equals(version)) {
			repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByUserIdAndCreditCardNumberAndTaskStatusAndTaskTypeAndOrderStatusAndVersion(userId, creditCardNumber, 2, 2, 0, version);
		}else {
			repaymentTaskPOJO = this.genreateRepaymentTaskPOJO(creditCardAccount,version,amount);
		}
		if (repaymentTaskPOJO == null) {
			map.put(CommonConstants.RESP_CODE, CommonConstants.FALIED);
			map.put(CommonConstants.RESP_MESSAGE, "生成任务失败,无法进行出款");
			return map;
		}

		List<RepaymentTaskPOJO> repaymentTaskPOJOs = new ArrayList<>();
		repaymentTaskPOJOs.add(repaymentTaskPOJO);
		this.executeTask(repaymentTaskPOJOs,"1".equals(isT1));
		map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
		map.put(CommonConstants.RESP_MESSAGE, "出款任务执行中");
		map.put(CommonConstants.RESULT, repaymentTaskPOJO);
		return map;
	}

	/**
	 * version2对首笔验证的冻结余额转入到余额的定时器
	 */
	@Scheduled(cron = "0 0/20 * * * ?")
	public void autoUpdateTaskType0OrderStatus4ConsumeTaskVersion2(){
		if ("true".equals(propertiesConfig.getScanOnOff())) {
			List<CreditCardManagerConfig> configs = this.getConfig();
			for (CreditCardManagerConfig creditCardManagerConfig : configs) {
				if (1 == creditCardManagerConfig.getScanOnOff()) {
					LOG.info("====================version"+creditCardManagerConfig.getVersion()+"修改首笔还款任务状态开始执行====================");
					this.checkTaskType0RepaymentTaskByVersion(creditCardManagerConfig.getVersion());
				}
			}
		}
	}
	
	/**
	 * 对还款失败但没有修改状态的任务进行修改
	 */
	@Scheduled(cron = "0 0/21 * * * ?")
	public void autoUpdateTaskType2OrderStatus4ConsumeTaskVersion2(){
		if ("true".equals(propertiesConfig.getScanOnOff())) {
			List<CreditCardManagerConfig> configs = this.getConfig();
			for (CreditCardManagerConfig creditCardManagerConfig : configs) {
				if (1 == creditCardManagerConfig.getScanOnOff()) {
					LOG.info("====================修改还款version"+creditCardManagerConfig.getVersion()+"失败任务状态开始执行====================");
					this.checkTaskType2OrderStatus4RepaymentTaskByVersion(creditCardManagerConfig.getVersion());
					this.checkTaskType1OrderStatus4RepaymentTaskByVersion(creditCardManagerConfig.getVersion());
				}
			}
		}
	}
	
	/**
	 * 执行还款任务定时器
	 */
	@Scheduled(cron = "0 0/5 8-23 * * ?")
	public void autoScanTaskType2AndTaskStatus0RepaymentTaskVersion2() {
		if ("true".equals(propertiesConfig.getScanOnOff())) {
			List<CreditCardManagerConfig> configs = this.getConfig();
			for (CreditCardManagerConfig creditCardManagerConfig : configs) {
				if (1 == creditCardManagerConfig.getScanOnOff()) {
					LOG.info("====================version"+creditCardManagerConfig.getVersion()+"还款任务开始执行====================");
					this.executeTask(this.findTaskType2AndTaskStatus0RepaymentTask(creditCardManagerConfig.getVersion()),false);
				}
			}
		}
	}

	
	/**
	 * 获取还款配置
	 * @return
	 */
	private List<CreditCardManagerConfig> getConfig(){
		List<CreditCardManagerConfig> creditCardManagerConfigs = creditCardManagerConfigBusiness.findAll();
		return creditCardManagerConfigs;
	}
	
	
	/**
	 * version1对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 15 22 * * ?")
	public void autoScanCreditCardAccountBlanceNotZero() {
//		this.executeRepaymentByBlanceThan0("1");
		this.executeRepaymentByBlanceThan0("6");
	}
	/**
	 * version1对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 00 07 * * ?")
	public void autoScanCreditCardAccountBlanceNotZero2() {
//		this.executeRepaymentByBlanceThan0("1");
		this.executeRepaymentByBlanceThan0("6");
	}
	/**
	 * version2对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 15 20 * * ?")
	public void autoScanCreditCardAccountBlanceNotZeroVersion2() {
		this.executeRepaymentByBlanceThan0("2");
	}
	/**
	 * version2对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 15 09 * * ?")
	public void autoScanCreditCardAccountBlanceNotZero2Version2() {
		this.executeRepaymentByBlanceThan0("2");
	}
	/**
	 * version3对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 10 09 * * ?")
	public void autoScanCreditCardAccountBlanceNotZeroVersion3() {
		this.executeRepaymentByBlanceThan0("3");
		this.executeRepaymentByBlanceThan0("5");
	}
	/**
	 * version3对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 50 20 * * ?")
	public void autoScanCreditCardAccountBlanceNotZero2Version3() {
		this.executeRepaymentByBlanceThan0("3");
		this.executeRepaymentByBlanceThan0("5");
	}
	/**
	 * version4对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 0 09 * * ?")
	public void autoScanCreditCardAccountBlanceNotZeroVersion4() {
		this.executeRepaymentByBlanceThan0("4");
	}
	/**
	 * version4对帐户余额有钱的帐户自动执行出款定时器
	 */
	@Scheduled(cron = "0 0 21 * * ?")
	public void autoScanCreditCardAccountBlanceNotZero2Version4() {
		this.executeRepaymentByBlanceThan0("4");
	}
	

	private void executeRepaymentByBlanceThan0(String version){
		if ("true".equals(propertiesConfig.getScanOnOff())) {
			this.clearCreditAccountFreezeBlance(version);
			int page = 0;
			List<RepaymentTaskPOJO> findCreditCardAccountBlanceNotZero = new ArrayList<>();
			CreditCardManagerConfig cardManagerConfig = creditCardManagerConfigBusiness.findByVersion(version);
			if (1 == cardManagerConfig.getScanOnOff()) {
				int firstMoney = cardManagerConfig.getFirstMoney();
				do{
					Pageable pageable = new PageRequest(page, 20, new Sort(Sort.Direction.DESC, "blance"));
					findCreditCardAccountBlanceNotZero = this.findCreditCardAccountBlanceNotZero(BigDecimal.valueOf(firstMoney),version,pageable);
					if (findCreditCardAccountBlanceNotZero != null && findCreditCardAccountBlanceNotZero.size() > 0) {
						this.executeTask(findCreditCardAccountBlanceNotZero,false);
					}
					page += 1;
				}while(findCreditCardAccountBlanceNotZero != null && findCreditCardAccountBlanceNotZero.size() > 0);
			}
		}
	}
	
	
	/**
	 * 获取当天当前时间之前批量生成的未执行还款任务
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param version
	 * @return
	 */
	private List<RepaymentTaskPOJO> findTaskType2AndTaskStatus0RepaymentTask(String version) {
		List<RepaymentTaskPOJO> repaymentTaskPOJOs = repaymentTaskPOJOBusiness.findTaskType2AndTaskStatus0RepaymentTaskAndVersion(version);
		return repaymentTaskPOJOs;
	}

	/**
	 * 获取帐户中blance大于0的帐户并生成自动出款任务
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param version
	 * @param pageable
	 * @return
	 */
	private List<RepaymentTaskPOJO> findCreditCardAccountBlanceNotZero(BigDecimal firstAmount,String version,Pageable pageable) {
		List<CreditCardAccount> creditCardAccounts = creditCardAccountBusiness.findCreditCardAccountByBlanceNotZeroAndVersion(version,pageable);
		List<RepaymentTaskPOJO> repaymentTaskPOJOs = null;
		if (creditCardAccounts != null && creditCardAccounts.size() > 0) {
			repaymentTaskPOJOs = new ArrayList<>();
			RepaymentTaskPOJO genreateRepaymentTaskPOJO;
			for (CreditCardAccount creditCardAccount : creditCardAccounts) {
				if (firstAmount.compareTo(creditCardAccount.getBlance()) < 0) {
					if (CardConstss.CARD_VERSION_6.equals(version)) {
						genreateRepaymentTaskPOJO = repaymentTaskPOJOBusiness.findByUserIdAndCreditCardNumberAndTaskStatusAndTaskTypeAndOrderStatusAndVersion(creditCardAccount.getUserId(), creditCardAccount.getCreditCardNumber(), 2, 2, 0, version);
					}else {
						genreateRepaymentTaskPOJO = this.genreateRepaymentTaskPOJO(creditCardAccount,version,null);
					}
					if (genreateRepaymentTaskPOJO != null) {
						repaymentTaskPOJOs.add(genreateRepaymentTaskPOJO);
					}
				}
			}
		}
		return repaymentTaskPOJOs;
	}

	/**
	 * 多线程执行扫描到的任务
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param repaymentTaskPOJOs
	 */
	public void executeTask(List<RepaymentTaskPOJO> repaymentTaskPOJOs,boolean isT1) {
		ApplicationContext applicationContext = this.getApplicationContext();
		CreditCardAccount creditCardAccount = null;
		ThreadRepaymentExecutor threadRepaymentExecutor = null;
		if (repaymentTaskPOJOs != null && repaymentTaskPOJOs.size() > 0) {
			RepaymentTaskPOJO repaymentTaskPOJO = null;
			for (int i = 0;i < repaymentTaskPOJOs.size();i++) {
				repaymentTaskPOJO = repaymentTaskPOJOs.get(i);
				creditCardAccount = creditCardAccountBusiness.findByUserIdAndCreditCardNumberAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(),repaymentTaskPOJO.getVersion());
				repaymentTaskPOJO.setRealAmount(creditCardAccount.getBlance());
				threadRepaymentExecutor = applicationContext.getBean(ThreadRepaymentExecutor.class);
				threadRepaymentExecutor.setRepaymentTaskPOJO(repaymentTaskPOJO);
				threadRepaymentExecutor.setIsT1(isT1);
				new Thread(threadRepaymentExecutor).start();
				LOG.info("执行任务=============================="+repaymentTaskPOJO);
				if( i != 0 && i % 10 ==0){
					long time = System.currentTimeMillis();
					boolean isTrue = true;
					while(isTrue){
						if(System.currentTimeMillis() - time >= 10000){
							isTrue = false;
						}
					}
				}
			}
		}
	}

	
	/**
	 * 创建出款任务
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param creditCardAccount
	 * @param version
	 * @return
	 */
	public RepaymentTaskPOJO genreateRepaymentTaskPOJO(CreditCardAccount creditCardAccount,String version,BigDecimal amount) {
		if (amount == null) {
			amount = creditCardAccount.getBlance();
		}
		String userId = creditCardAccount.getUserId();
		String creditCardNumber = creditCardAccount.getCreditCardNumber();
		String description = "尾号" + creditCardNumber.substring(creditCardNumber.length() - 4) + "|系统自动生成出款任务";
		// String executeDate = DateUtil.getDateStringConvert(new String(), new
		// Date(), "yyyy-MM-dd");
		String createTime = null;
		String channelId = null;
		String channelTag = null;
		BigDecimal serviceCharge = BigDecimal.ZERO;
		BigDecimal rate = BigDecimal.ZERO;
		BigDecimal returnServiceCharge = BigDecimal.ZERO;
		List<RepaymentTaskPOJO> repaymentTaskPOJOs = repaymentTaskPOJOBusiness.findByExecuteDateAndVersion(userId,creditCardNumber,version);
		if (repaymentTaskPOJOs != null && repaymentTaskPOJOs.size() > 0) {
			createTime = repaymentTaskPOJOs.get(0).getCreateTime();
			serviceCharge = repaymentTaskPOJOs.get(0).getServiceCharge();
			rate = repaymentTaskPOJOs.get(0).getRate();
			channelId = repaymentTaskPOJOs.get(0).getChannelId();
			channelTag = repaymentTaskPOJOs.get(0).getChannelTag();
			createTime = createTime == null? DateUtil.getDateStringConvert(new String(), new Date(), "yyyy-MM-dd HH:mm:ss") : createTime;
			RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.createNewRepaymentTaskPOJO(amount, userId,creditCardNumber, 1, description, createTime, serviceCharge, rate, returnServiceCharge, channelId,channelTag,version);
			return repaymentTaskPOJO;
		} else {
//			createTime = DateUtil.getDateStringConvert(new String(), new Date(), "yyyy-MM-dd HH:mm:ss");
//			channelId = repaymentChannelIdWhole;
//			channelTag = repaymentChannelTagWhole;
//			RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.createNewRepaymentTaskPOJO(amount, userId,creditCardNumber, 1, description, createTime, serviceCharge, rate, returnServiceCharge, channelId,channelTag,version);
//			return repaymentTaskPOJO;
			return null;
		}

	}
	
	/**
	 * 解除冻结余额
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param version
	 */
	public void clearCreditAccountFreezeBlance(String version){
		List<CreditCardAccount> creditCardAccounts = creditCardAccountBusiness.findByFreezeBlanceGreaterThan0AndVersion(version);		
		if(creditCardAccounts!=null && creditCardAccounts.size() > 0){
			for(CreditCardAccount creditCardAccount:creditCardAccounts){
				RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByUserIdAndCreditCardNumberAndTaskStatusAndTaskTypeAndOrderStatusAndVersion(creditCardAccount.getUserId(), creditCardAccount.getCreditCardNumber(), 1, 2, 4, version);
				if (repaymentTaskPOJO != null) {
					this.checkTaskType2OrderStatus4RepaymentTask(repaymentTaskPOJO);
				}
			}
		}
	}
	
	/*public void clearCreditAccountFirstFreezeBlance(String version){
		List<CreditCardAccount> creditCardAccounts = creditCardAccountBusiness.findByFreezeBlanceAndVersion(BigDecimal.valueOf(10),version);
		LOG.info("creditCardAccounts====" + creditCardAccounts);
		if(creditCardAccounts!=null && creditCardAccounts.size() > 0){
			for(CreditCardAccount creditCardAccount:creditCardAccounts){
				RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByCreditCardNumberAndTaskTypeAndVersion(creditCardAccount.getCreditCardNumber(), 0,creditCardAccount.getVersion());
				LOG.info("repaymentTaskPOJO====" + repaymentTaskPOJO);
				List<CreditCardAccountHistory creditCardAccountHistory = creditCardAccountHistoryBusiness.findByTaskIdAndAddOrSub(repaymentTaskPOJO.getRepaymentTaskId(), 1);
				LOG.info("creditCardAccountHistory====" + creditCardAccountHistory);
				if(creditCardAccountHistory != null  && repaymentTaskPOJO.getOrderStatus().intValue() != 1){
					creditCardAccountHistory.setAddOrSub(7);
					creditCardAccountHistoryBusiness.save(creditCardAccountHistory);
					Date createTime = creditCardAccountHistory.getCreateTime();
					Calendar calendar = Calendar.getInstance();
					calendar.setTime(new Date());
					calendar.add(Calendar.MINUTE, -20);
					Calendar calendar2 = Calendar.getInstance();
					calendar2.setTime(createTime);
					LOG.info("calendar.compareTo(calendar2) >= 0)====" + calendar.compareTo(calendar2));
					if(calendar.compareTo(calendar2) >= 0){
						repaymentTaskPOJO.setTaskStatus(0);
						repaymentTaskPOJO.setOrderStatus(0);
						repaymentTaskPOJO = repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
						creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(), 3, repaymentTaskPOJO.getRealAmount(), "首笔还款失败,增加余额",repaymentTaskPOJO.getVersion());
					}
				}else if(repaymentTaskPOJO.getOrderStatus().intValue() == 1){
					creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(), 4, repaymentTaskPOJO.getRealAmount(), "还款成功,扣除冻结费用",repaymentTaskPOJO.getVersion());
				}
			}
		}
	}*/
	
/*	public void updateRepaymentTaskRealAmount(String executeDate,int orderStatus,String version){
		List<RepaymentTaskPOJO>  repaymentTaskPOJOs= repaymentTaskPOJOBusiness.findByExecuteDateAndOrderStatusAndVersion(executeDate,orderStatus,version);
		if(repaymentTaskPOJOs!=null && repaymentTaskPOJOs.size() > 0){
			for(RepaymentTaskPOJO repaymentTaskPOJO:repaymentTaskPOJOs){
				if(BigDecimal.ZERO.compareTo(repaymentTaskPOJO.getRealAmount()) == 0){
					CreditCardAccountHistory creditCardAccountHistory = creditCardAccountHistoryBusiness.findByTaskIdAndAddOrSub(repaymentTaskPOJO.getRepaymentTaskId(), 1);
					if(creditCardAccountHistory != null){
						repaymentTaskPOJO.setRealAmount(creditCardAccountHistory.getAmount());
						repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
					}
				}
			}
		}
	}*/
	
	/*private void returnServiceCharge(ConsumeTaskPOJO consumeTaskPOJO,RepaymentTaskPOJO repaymentTaskPOJO){
//		RepaymentTaskPOJO repaymentTaskPOJO = repaymentTaskPOJOBusiness.findByRepaymentTaskId(consumeTaskPOJO.getRepaymentTaskId());
		BigDecimal consumeReturnServiceCharge = consumeTaskPOJO.getAmount().multiply(repaymentTaskPOJO.getRate());
		repaymentTaskPOJO.setReturnServiceCharge(repaymentTaskPOJO.getReturnServiceCharge().add(consumeReturnServiceCharge).setScale(2, BigDecimal.ROUND_DOWN));
		repaymentTaskPOJO = repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
		creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(), consumeTaskPOJO.getConsumeTaskId(),5, consumeReturnServiceCharge, "消费失败退还手续费",repaymentTaskPOJO.getVersion());
		consumeTaskPOJO.setTaskStatus(2);
		consumeTaskPOJO.setOrderStatus(0);
		consumeTaskPOJO.setReturnMessage("扣款失败");
		consumeTaskPOJO.setRealAmount(BigDecimal.ZERO);
		consumeTaskPOJOBusiness.save(consumeTaskPOJO);
	}*/
	
	/**
	 * 修改Version2首笔还款失败的任务状态
	 */
/*	private void checkTaskType0RepaymentTaskVersion2(){
		List<RepaymentTaskPOJO> repaymentTaskPOJOs = repaymentTaskPOJOBusiness.findByTaskTypeAndOrderStatusAndVersion(0,4,"2");
		if(repaymentTaskPOJOs !=null && repaymentTaskPOJOs.size() > 0){
			for(RepaymentTaskPOJO repaymentTaskPOJO:repaymentTaskPOJOs){
				JSONObject resultJSON = baseExecutor.getOrderStatusByVersion(repaymentTaskPOJO.getOrderCode(), CommonConstants.ORDER_TYPE_REPAYMENT, repaymentTaskPOJO.getVersion());
				if(!CommonConstants.SUCCESS.equals(resultJSON.get(CommonConstants.RESP_CODE)) && !CardConstss.WAIT_NOTIFY.equals(resultJSON.get(CommonConstants.RESP_CODE))){
					LOG.info(repaymentTaskPOJO.toString() + "将该首笔还款任务修改为失败" + "|查询订单结果为:" + resultJSON);
					repaymentTaskPOJO.setTaskStatus(0);
					repaymentTaskPOJO.setOrderStatus(0);
					repaymentTaskPOJO.setReturnMessage(resultJSON.containsKey(CommonConstants.RESP_MESSAGE)?resultJSON.getString(CommonConstants.RESP_MESSAGE):"还款失败!");
					repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
					creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(), 3, repaymentTaskPOJO.getRealAmount(), "首笔还款失败,解除冻结金额", repaymentTaskPOJO.getVersion());
				}else if (CommonConstants.SUCCESS.equals(resultJSON.get(CommonConstants.RESP_CODE))) {
					LOG.info(repaymentTaskPOJO.toString() + "将该首笔还款任务修改为成功" + "|查询订单结果为:" + resultJSON);
					creditCardManagerTaskService.updateTaskStatusByOrderCode(null, repaymentTaskPOJO.getOrderCode(), "2");
					JSONObject updateOrderJSONObject = baseExecutor.updatePaymentOrderByOrderCode(repaymentTaskPOJO.getOrderCode());
					LOG.info("修改订单状态结果:" + updateOrderJSONObject.toString());
				}
			}
		}
	}*/
	
	
	/**
	 * 修改首笔还款待完成的任务状态
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param version
	 */
	private void checkTaskType0RepaymentTaskByVersion(String version){
		List<RepaymentTaskPOJO> repaymentTaskPOJOs = repaymentTaskPOJOBusiness.findByTaskTypeAndOrderStatusAndVersion(0,4,version);
		if(repaymentTaskPOJOs !=null && repaymentTaskPOJOs.size() > 0){
			for(RepaymentTaskPOJO repaymentTaskPOJO:repaymentTaskPOJOs){
				JSONObject resultJSON = null;
				String respCode = "";
				String respMessage = "";
				try {
					resultJSON = baseExecutor.getOrderStatusByVersion(repaymentTaskPOJO.getOrderCode(), CommonConstants.ORDER_TYPE_REPAYMENT, repaymentTaskPOJO.getVersion());
					respCode = resultJSON.getString(CommonConstants.RESP_CODE);
					respMessage = (resultJSON.containsKey(CommonConstants.RESP_MESSAGE)?resultJSON.getString(CommonConstants.RESP_MESSAGE):"还款失败!");
				} catch (RuntimeException e) {
					LOG.info("查询异常.将该首笔还款任务修改为失败=====" + repaymentTaskPOJO.toString());
					e.printStackTrace();
					respCode = CommonConstants.FALIED;
					respMessage = "还款失败!";
				}
				Date orderExecuteTime = DateUtil.getDateStringConvert(new Date(), repaymentTaskPOJO.getOrderCode().subSequence(0, 10), "yyyyMMddHH");
				Calendar calendar = Calendar.getInstance();
				calendar.set(Calendar.HOUR_OF_DAY, -6);
				if(CommonConstants.FALIED.equals(respCode) || (CardConstss.WAIT_NOTIFY.equals(respCode) && calendar.getTime().compareTo(orderExecuteTime) > 0)){
					LOG.info(repaymentTaskPOJO.toString() + "将该首笔还款任务修改为失败" + "|查询订单结果为:" + resultJSON);
					repaymentTaskPOJO.setTaskStatus(0);
					repaymentTaskPOJO.setOrderStatus(0);
					repaymentTaskPOJO.setReturnMessage(respMessage);
					repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
					creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(), repaymentTaskPOJO.getRepaymentTaskId(), 3, repaymentTaskPOJO.getRealAmount(), "首笔还款失败,解除冻结金额", repaymentTaskPOJO.getVersion());
				}else if (CommonConstants.SUCCESS.equals(respCode)) {
					LOG.info(repaymentTaskPOJO.toString() + "将该首笔还款该任务修改为成功" + "|查询订单结果为:" + resultJSON);
					creditCardManagerTaskService.updateTaskStatusByOrderCode(null, repaymentTaskPOJO.getOrderCode(),repaymentTaskPOJO.getVersion());
					JSONObject updateOrderJSONObject = baseExecutor.updatePaymentOrderByOrderCode(repaymentTaskPOJO.getOrderCode());
					LOG.info("修改订单状态结果:" + updateOrderJSONObject.toString());
				}
			}
		}
	}
	
	/**
	 * 校验待完成的批量生成的任务
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param version
	 */
	private void checkTaskType2OrderStatus4RepaymentTaskByVersion(String version){
		List<RepaymentTaskPOJO> version1RepaymentTaskPOJOs = repaymentTaskPOJOBusiness.findByTaskTypeAndOrderStatusAndVersion(2, 4,version);
		for(RepaymentTaskPOJO repaymentTaskPOJO:version1RepaymentTaskPOJOs){
			this.checkTaskType2OrderStatus4RepaymentTask(repaymentTaskPOJO);
		}
	}
	
	/**
	 * 校验自动生成的任务
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月14日  
	 * @param version
	 */
	private void checkTaskType1OrderStatus4RepaymentTaskByVersion(String version){
		List<RepaymentTaskPOJO> version1RepaymentTaskPOJOs = repaymentTaskPOJOBusiness.findByTaskTypeAndOrderStatusAndVersion(1, 4,version);
		for(RepaymentTaskPOJO repaymentTaskPOJO:version1RepaymentTaskPOJOs){
			this.checkTaskType2OrderStatus4RepaymentTask(repaymentTaskPOJO);
		}
	}
	
	/**
	 * 具体校验方法
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param repaymentTaskPOJO
	 */
	private void checkTaskType2OrderStatus4RepaymentTask(RepaymentTaskPOJO repaymentTaskPOJO){
		JSONObject resultJSON = null;
		String respCode = "";
		String respMessage = "";
		try {
			resultJSON = baseExecutor.getOrderStatusByVersion(repaymentTaskPOJO.getOrderCode(),  CommonConstants.ORDER_TYPE_REPAYMENT, repaymentTaskPOJO.getVersion());
			respCode = resultJSON.getString(CommonConstants.RESP_CODE);
			respMessage = (resultJSON.containsKey(CommonConstants.RESP_MESSAGE)?resultJSON.getString(CommonConstants.RESP_MESSAGE):"还款失败!");
		} catch (RuntimeException e) {
			LOG.info("查询异常.将该笔还款任务修改为失败=====" + repaymentTaskPOJO.toString());
			e.printStackTrace();
			respCode = CommonConstants.FALIED;
			respMessage = "还款失败!";
		}
		String executeDateTime = repaymentTaskPOJO.getExecuteDateTime();
		Date orderExecuteTime = DateUtil.getDateStringConvert(new Date(), executeDateTime, "yyyy-MM-dd HH:mm:ss");
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, -6);
		if(CommonConstants.FALIED.equals(respCode) || (CardConstss.WAIT_NOTIFY.equals(respCode) && calendar.getTime().compareTo(orderExecuteTime) > 0)){
			LOG.info(repaymentTaskPOJO.toString() + "将该还款任务修改为失败" + "|查询订单结果为:" + resultJSON);
			repaymentTaskPOJO.setTaskStatus(2);
			repaymentTaskPOJO.setOrderStatus(0);
			repaymentTaskPOJO.setRealAmount(BigDecimal.ZERO);
			repaymentTaskPOJO.setReturnMessage(respMessage);
			repaymentTaskPOJOBusiness.save(repaymentTaskPOJO);
			creditCardAccountBusiness.updateCreditCardAccountAndVersion(repaymentTaskPOJO.getUserId(), repaymentTaskPOJO.getCreditCardNumber(),repaymentTaskPOJO.getRepaymentTaskId(),3,repaymentTaskPOJO.getRealAmount(),"还款失败增加余额",repaymentTaskPOJO.getVersion());
			util.pushMessage(repaymentTaskPOJO.getUserId(),"您有一笔金额为:"+repaymentTaskPOJO.getAmount()+"的还款任务失败,系统将在当天23:00前进行还款!");
		}else if (CommonConstants.SUCCESS.equals(respCode)) {
			LOG.info(repaymentTaskPOJO.toString() + "将该还款任务修改为成功" + "|查询订单结果为:" + resultJSON);
			creditCardManagerTaskService.updateTaskStatusByOrderCode(null, repaymentTaskPOJO.getRepaymentTaskId(),repaymentTaskPOJO.getVersion());
			JSONObject updateOrderJSONObject = baseExecutor.updatePaymentOrderByOrderCode(repaymentTaskPOJO.getRepaymentTaskId());
			LOG.info("修改订单状态结果:" + updateOrderJSONObject.toString());
		}
	}
	
	@RequestMapping(method = RequestMethod.POST, value = "/v1.0/creditcardmanager/testExecuteFirstRepayment")
	public @ResponseBody Object testExecuteFirstRepayment(HttpServletRequest request,
			@RequestParam(value="version",required=false,defaultValue="1")String version
			) {
		this.checkTaskType2OrderStatus4RepaymentTaskByVersion(version);
		return "OK";
	}
	
	/**
	 * 执行首笔验证出款任务
	 * @author Robin-QQ/WX:354476429 
	 * @date 2018年6月12日  
	 * @param version
	 */
	private void executeFirstRepayment(String version){
		CreditCardManagerConfig creditCardManagerConfig = creditCardManagerConfigBusiness.findByVersion(version);
		if (creditCardManagerConfig == null) {
			creditCardManagerConfig = new CreditCardManagerConfig();
			creditCardManagerConfig.setFirstMoney(10);
		}
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, -1);
		Date time = calendar.getTime();
		List<CreditCardAccount> creditCardAccounts = creditCardAccountBusiness.findByBlanceAndVersionAndLastUpdateTimeLessThan(BigDecimal.valueOf(creditCardManagerConfig.getFirstMoney()),version,time);
		for(CreditCardAccount creditCardAccount:creditCardAccounts){
			RestTemplate restTemplate = new RestTemplate();
			LinkedMultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
			requestEntity.add("userId", creditCardAccount.getUserId());
			requestEntity.add("creditCardNumber", creditCardAccount.getCreditCardNumber());
			requestEntity.add("phone", creditCardAccount.getPhone());
			requestEntity.add("brandId", "2");
			requestEntity.add("version", version);
			String url = "http://106.15.47.73/v1.0/creditcardmanager/first/use/credit/card/manager";
			String postForObject;
			try {
				postForObject = restTemplate.postForObject(url, requestEntity, String.class);
			} catch (RestClientException e) {
				System.out.println(creditCardAccount.getCreditCardNumber() + "==================失败");
				continue;
			}
			System.out.println(creditCardAccount.getCreditCardNumber() + "==================" +postForObject);
		}
		System.out.println(creditCardAccounts.size());
	
	}
	
}
